package com.beamfield.controller.manage.material;

import com.alibaba.fastjson.JSON;
import com.beamfield.common.ApiResult;
import com.beamfield.common.ExcelExport;
import com.beamfield.common.PageResult;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.Project;
import com.beamfield.model.PurchaseDetail;
import com.beamfield.model.PurchasePlan;
import com.beamfield.model.Supplies;
import com.beamfield.modelVo.PurchaseDetailVo;
import com.beamfield.modelVo.SuppliesDemandVo;
import com.beamfield.service.manage.sys.ProjectService;
import com.beamfield.service.manage.sys.SuppliesService;
import com.beamfield.service.manage.material.PurchaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购管理
 */
@Controller
@RequestMapping("/cms/material/purchase")
public class PurchaseController {

    private final ProjectService projectService;
    private final PurchaseService purchaseService;
    private final SuppliesService suppliesService;
    @Value("${session.beam}")
    private String beam;
    @Value("${session.user}")
    private String user;

    @Autowired
    public PurchaseController(ProjectService projectService,
                              PurchaseService purchaseService,
                              SuppliesService suppliesService) {
        this.projectService = projectService;
        this.purchaseService = purchaseService;
        this.suppliesService = suppliesService;
    }

    @RequestMapping(value = "/purchase_list", method = RequestMethod.GET)
    public ModelAndView purchase() {
        return new ModelAndView();
    }

    @RequestMapping(value = "/addPurchase", method = RequestMethod.GET)
    public ModelAndView addPurchase() {
        return new ModelAndView();
    }

    @RequestMapping(value = "/purchaseDetails", method = RequestMethod.GET)
    public ModelAndView details() {
        return new ModelAndView();
    }

    /**
     * 获取物资首页统计数据
     */
    @RequestMapping("readMaterialStatistics")
    @ResponseBody
    public ApiResult readMaterialStatistics(HttpSession session){
        long beamId = (long) session.getAttribute(this.beam);
        Map<String, Object> map = purchaseService.readMaterialStatistics(beamId);
        return new ApiResult(map);
    }

    /**
     * 获取项目列表
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/projectList", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult projectList(HttpSession session) {
        ApiResult apiResult = new ApiResult();
        long beamId = (long) session.getAttribute(this.beam);
        List<Project> projectList = null;
        try {
            projectList = projectService.getProjectR(beamId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        apiResult.setResult(projectList);
        return apiResult;
    }

    /**
     * 获取采购计划
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/readPurchaseData", method = RequestMethod.GET)
    @ResponseBody
    public PageResult purchaseList(HttpServletRequest request) {
        long beamId = (long) request.getSession().getAttribute(this.beam);
        String projectId = request.getParameter("projectId");
        String purchaseName = request.getParameter("purchaseName");
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        String purchaseState = request.getParameter("purchaseState");
        List<PurchasePlan> purchasePlanList = purchaseService.getPurchase(projectId, purchaseName, purchaseState, offset, limit, beamId);
        long total = purchaseService.countPurchase(projectId, purchaseName, purchaseState, beamId);

        return new PageResult(total, Long.parseLong(offset), purchasePlanList);
    }

    /**
     * 获取采购计划月份
     * @param projectId
     * @return
     */
    @RequestMapping(value = "/getPurchaseMonth")
    @ResponseBody
    public ApiResult getPurchaseMonth(String projectId, HttpServletRequest request){
        long beamId = (long) request.getSession().getAttribute(this.beam);
        if(StringUtils.isEmpty(projectId)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        try {
            return purchaseService.getPurchaseMonth(projectId, beamId);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 导出采购计划Excel
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportPurchaseData")
    public String exportPurchaseData(HttpServletRequest request, HttpServletResponse response){
        long beamId = (long) request.getSession().getAttribute(this.beam);
        String purchaseId = request.getParameter("purchaseId");
        String projectId = request.getParameter("projectId");
        if(StringUtils.isEmpty(purchaseId)||StringUtils.isEmpty(projectId)){
            return null;
        }
        try {
            purchaseService.exportPurchaseData(purchaseId, projectId, response, beamId);
        }catch (Exception e){
            e.printStackTrace();
            return "系统错误";
        }
        return "成功";
    }
    /**
     * 导出总采购计划
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportAllPurchase")
    public String exportAllPurchase(HttpServletRequest request, HttpServletResponse response){
        long beamId = (long) request.getSession().getAttribute(this.beam);
        String projectId = request.getParameter("projectId");
        if(StringUtils.isEmpty(projectId)){
            return null;
        }
        try {
            purchaseService.exportAllPurchase(projectId, response, beamId);
        }catch (Exception e){
            e.printStackTrace();
            return "系统错误";
        }
        return "成功";
    }

    /**
     * 导出总采购计划
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportOnePurchase")
    public String exportOnePurchase(HttpServletRequest request, HttpServletResponse response){
        long beamId = (long) request.getSession().getAttribute(this.beam);
        String projectId = request.getParameter("projectId");
        String demandId = request.getParameter("demandId");
        if(StringUtils.isEmpty(projectId)){
            return null;
        }
        try {
            purchaseService.exportOnePurchase(projectId, response, beamId,demandId);
        }catch (Exception e){
            e.printStackTrace();
            return "系统错误";
        }
        return "成功";
    }
    /**
     * 导出月采购计划
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportMonthPurchase")
    public String exportMonthPurchase(HttpServletRequest request, HttpServletResponse response){
        String projectId = request.getParameter("projectId");
        String month = request.getParameter("month");
        if(StringUtils.isEmpty(projectId) || StringUtils.isEmpty(month)){
            return null;
        }
        long beamId = (long) request.getSession().getAttribute(this.beam);
        try {
            purchaseService.exportMonthPurchase(projectId, month, response, beamId);
        }catch (Exception e){
            e.printStackTrace();
            return "系统错误";
        }
        return "成功";
    }
    /**
     * 获取采购计划明细列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/readPurchaseDetailsData", method = RequestMethod.GET)
    @ResponseBody
    public PageResult purchaseDetailsList(HttpServletRequest request) {
        String purchaseId = request.getParameter("purchaseId");
        String projectId = request.getParameter("projectId");
        if(StringUtils.isEmpty(purchaseId)||StringUtils.isEmpty(projectId)){
            return null;
        }
        String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        String suppliesName = request.getParameter("suppliesName");
        String detailsState = request.getParameter("detailsState");
        List<PurchaseDetailVo> purchaseDetailVoList = purchaseService.getPurchaseDetails(purchaseId, suppliesName, offset, limit, detailsState, projectId);
        long total = purchaseService.countPurchaseDetails(purchaseId, suppliesName, detailsState);
        if(offset==null){
            offset = "-1";
        }
        return new PageResult(total, Long.parseLong(offset), purchaseDetailVoList);
    }

    /**
     * 获取材料需求量和已采购量
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSuppliesDemand", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getSuppliesDemand(HttpServletRequest request){
        ApiResult apiResult = new ApiResult();
        String projectId = request.getParameter("projectId");
        String suppliesId = request.getParameter("suppliesId");
        String demandId = request.getParameter("demandId");
        if(StringUtils.isEmpty(projectId)||StringUtils.isEmpty(suppliesId) || StringUtils.isEmpty(demandId)){
            apiResult.setCode(HttpResultEnum.MIS_PARAM.getCode());
            apiResult.setMessage(HttpResultEnum.MIS_PARAM.getMessage());
            return apiResult;
        }
        SuppliesDemandVo suppliesDemandVo = purchaseService.getSuppliesDemand(projectId, demandId, suppliesId);
        apiResult.setResult(suppliesDemandVo);
        return apiResult;
    }

    /**
     * 获取distinct材料
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSuppliesName", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getSuppliesName(HttpSession session, HttpServletRequest request) {
        ApiResult apiResult = new ApiResult();
        long beamId = (long) session.getAttribute(this.beam);
        String projectId = request.getParameter("projectId");
        List<Supplies> suppliesList = suppliesService.getSuppliesDistinctByNameAndMaterialName(null, beamId, projectId);
        apiResult.setResult(suppliesList);
        return apiResult;
    }
    /**
     * 根据材料名称获取材料
     *
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSupplies", method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getSupplies(HttpSession session, HttpServletRequest request) {
        ApiResult apiResult = new ApiResult();
        long beamId = (long) session.getAttribute(this.beam);
        String suppliesName = request.getParameter("suppliesName");
        String projectId = request.getParameter("projectId");
        List<Supplies> suppliesList = suppliesService.getSupplies(beamId, null, projectId, suppliesName);
        apiResult.setResult(suppliesList);
        return apiResult;
    }

    /**
     * 新增采购计划
     *
     * @param purchaseDetailJson 采购明细列表
     * @param purchaseName       采购计划名称
     * @param session
     * @return
     */
    @RequestMapping(value = "/doSave", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult doSave(String demand,String purchaseDetailJson, String purchaseName, String projectId, HttpSession session) {
        ApiResult apiResult = new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        long beamId = (long) session.getAttribute(this.beam);
        long userId = (long) session.getAttribute(this.user);
        if (StringUtils.isEmpty(purchaseDetailJson)) {
            apiResult.setResult(HttpResultEnum.MIS_PARAM.getCode());
            apiResult.setMessage(HttpResultEnum.MIS_PARAM.getMessage());
            return apiResult;
        }
        if (StringUtils.isEmpty(projectId)) {
            apiResult.setResult(HttpResultEnum.MIS_PARAM.getCode());
            apiResult.setMessage(HttpResultEnum.MIS_PARAM.getMessage());
            return apiResult;
        }
        if (StringUtils.isEmpty(purchaseName)) {
            apiResult.setResult(HttpResultEnum.MIS_PARAM.getCode());
            apiResult.setMessage("请输入采购计划名称");
            return apiResult;
        }
        try {
            List<PurchaseDetail> purchaseDetailList = JSON.parseArray(purchaseDetailJson, PurchaseDetail.class);
            if (purchaseDetailList == null || purchaseDetailList.isEmpty()) {
                return apiResult;
            }
            apiResult = purchaseService.save(purchaseDetailList, purchaseName, Long.parseLong(projectId), beamId, userId, demand);
        } catch (Exception e) {
            e.printStackTrace();
            apiResult.setCode(HttpResultEnum.EXCEPTION.getCode());
            apiResult.setMessage(HttpResultEnum.EXCEPTION.getMessage());
        }
        return apiResult;
    }

    /**
     * 审批采购计划
     * @param appr 1：通过 2：不通过
     * @param apprType 审批类型 f_appr:项目经理审批 s_appr:财务审批
     * @param purchaseId 采购计划id
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveAppr",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult saveAppr(Integer appr, String apprType, Long purchaseId, HttpServletRequest request,String f_back_reason){
        if (appr==2){
            if (StringUtils.isEmpty(f_back_reason)){
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), "请输入审批不通过理由");
            }
        }
        if(appr == null || StringUtils.isEmpty(apprType) || purchaseId == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        long userId = (long) request.getSession().getAttribute(this.user);
        long beamid = (long) request.getSession().getAttribute(this.beam);
        try {
            return purchaseService.saveAppr(appr, apprType, purchaseId, userId,f_back_reason,beamid);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    /**
     * 保存采购活动
     * @param active 1：直接购买 2：招标
     * @param purchaseId 采购计划id
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveActive",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult saveActive(Integer active, Long purchaseId, HttpServletRequest request){
        if(active == null || purchaseId == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        long userId = (long) request.getSession().getAttribute(this.user);
        long beam = (long) request.getSession().getAttribute(this.beam);
        try {
            return purchaseService.saveActive(active, purchaseId, userId,beam);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }
}
